package com.business.business.support.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Inet4Address;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;

public class Client {
    private static final int PORT = 1234;
    private static final int LOCAL_PORT = 20001;

    public static void main(String[] args) throws IOException {
        Socket  socket = new Socket();
        //设置读取超时时间为2秒
        socket.setSoTimeout(5000);
        // 是否需要在长时无数据响应时发送确认数据（类似心跳包），时间大约为2小时
        //socket.setKeepAlive(true);
        // 设置接收发送缓冲器大小
        socket.setReceiveBufferSize(64 * 1024 * 1024);
        socket.setSendBufferSize(64 * 1024 * 1024);
        // 绑定到本地20001端口
        socket.bind(new InetSocketAddress(Inet4Address.getLocalHost(), LOCAL_PORT));
        // 链接到本地20000端口，超时时间3秒，超过则抛出超时异常
        socket.connect(new InetSocketAddress(Inet4Address.getLocalHost(), PORT), 3000);

        System.out.println("已发起服务器连接，并进入后续流程～");
        System.out.println("客户端信息：" + socket.getLocalAddress() + " P:" + socket.getLocalPort());
        System.out.println("服务器信息：" + socket.getInetAddress() + " P:" + socket.getPort());

        try {
            // 发送接收数据
            todo(socket);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("异常关闭");
        }finally {
            // 释放资源
            socket.close();
            System.out.println("客户端已退出～");
        }
    }




    private static void todo(Socket client) throws IOException  {
        // 得到Socket输出流       , 输入流
        OutputStream outputStream  =  client.getOutputStream();
        InputStream inputStream = client.getInputStream();
        byte[] buffer = new byte[256];
        ByteBuffer byteBuffer = ByteBuffer.wrap(buffer);

        // int
        int i = 2323123;
        byteBuffer.putInt(i);

        // String
        String str = "Hello你好!";
        byteBuffer.put(str.getBytes());

        // 发送到服务器
        outputStream.write(buffer, 0, byteBuffer.position());

        // 接收服务器返回
        int read  = inputStream.read(buffer);
        System.out.println("收到数量：" + read);

        // 资源释放
        outputStream.close();
        inputStream.close();
    }
}